package com.komodo.island.gdx.game.underwater;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.actors.Image;
import com.komodo.island.gdx.Art;
import com.komodo.island.gdx.Constants;
import com.komodo.island.gdx.Input;
import com.komodo.island.gdx.KomodoIsland;
import com.komodo.island.gdx.Persistence;
import com.komodo.island.gdx.dialog.LoseDialog;
import com.komodo.island.gdx.dialog.WinDialog;
import com.komodo.island.gdx.game.Time;
import com.komodo.island.gdx.screen.Screen;
import com.komodo.island.gdx.screen.SlideScreen;

public class KomodoUnderwater extends SlideScreen {

	public static final int BARACUDDA = 11;
	public static final int DUGONG = 10;
	public static final int PARI = 9;
	public static final int GURITA = 8;
	public static final int EPHIPPIDEA = 7;
	public static final int BINTANG = 6;
	public static final int IKANKUNING = 0;
	public static final int IKANUNGU = 4;
	public static final int IKANBADUT = 3;
	public static final int IKANANEH = 2;
	public static final int IKANLUPA = 1;
	public static final int DOLPHIN = 5;

	public Sound click;
	public Music swype;

	private UnderwaterStage underwaterStage;
	private Random randomizer;

	private List<Fish> fishes;
	private int targetFish;
	public Time gameTime;
	public Time timer;
	private int gamePoint;
	private int targetPoint;
	private int seaWidth;

	private int genTargetCurSecond = -1;
	private int moveFishCurSecond = -1;

	public boolean shutterEffect = false;
	public double shutterStart;
	public double shutterCurr;

	public TextureRegion[][] fishRegion;
	private float stateTime;
	private Texture underwaterTexture;

	private TextureRegion background;
	private TextureRegion targetText;
	private TextureRegion targetFishReg;
	private TextureRegion pointText;
	private TextureRegion bgTime;

	public KomodoUnderwater() {
		ID = Input.SCREEN_GAME;

	}

	@Override
	public void init(KomodoIsland komodoIsland, Texture texture) {
		super.init(komodoIsland, texture);
		previousScreen = komodoIsland.touristScreen;

		seaWidth = Constants.GAME_WIDTH; // later replaced by width of sea
											// background (must be more than
											// device screen width)

		if (randomizer == null)
			randomizer = new Random();
		if (gameTime == null)
			gameTime = new Time(0, 59);
		fishes = new ArrayList<Fish>();

		usePage = false;

	}

	@Override
	protected void onGameRunning() {
		// TODO Auto-generated method stub
		// System.out.println(Gdx.graphics.getDeltaTime());
		// System.out.println("cekcek");

		camera.update();
		batch.setProjectionMatrix(camera.combined);

		stateTime += Gdx.graphics.getDeltaTime();
		gameTime.runTime();

		batch.begin();
		batch.draw(background, 0, 0);

		for (Fish fish : fishes) {
			// batch.draw(fish.tex, fish.x, fish.y);
			fish.draw(batch);
		}

		batch.end();
		underwaterStage.draw();
		// Art.drawString("1", 0, 0);
		// Art.drawString("1", 480 - 32, 0);

		// Art.drawString(underwaterStage.getSpriteBatch(), (xpos - 240) + "",
		// 480 - 150, 0);
		// Art.drawString(underwaterStage.getSpriteBatch(), (xpos + 240) + "",
		// 480 - 150, 50);
		// Art.drawString(underwaterStage.getSpriteBatch(), "target " +
		// targetFish
		// + "", 0, 320 - 50);
		// Art.drawString(underwaterStage.getSpriteBatch(), "point " + gamePoint
		// + "", 0, 320 - 100);
		// Art.drawString(underwaterStage.getSpriteBatch(), "score " + score +
		// "",
		// 0, 320 - 150);

		underwaterStage.getSpriteBatch().begin();
		underwaterStage.getSpriteBatch().draw(targetText, 0, 320 - 32 - 16);
		underwaterStage.getSpriteBatch().draw(targetFishReg, 96,
				320 - targetFishReg.getRegionHeight());
		underwaterStage.getSpriteBatch().draw(pointText,
				96 + targetFishReg.getRegionWidth(), 320 - 32 - 16);
		underwaterStage.getSpriteBatch().draw(bgTime, 0, 0);

		underwaterStage.getSpriteBatch().end();
		Art.drawString(underwaterStage.getSpriteBatch(), gamePoint + "",
				96 * 2 + targetFishReg.getRegionWidth(), 320 - 32 - 16);
//		System.out.println(gamePoint);
		Art.drawString(
				underwaterStage.getSpriteBatch(),
				"Time " + gameTime.getMinute() + ":"
						+ Art.decimal2.format(gameTime.getSecond()), 0, 0);

		// int index = 0;
		// for (Fish fish : fishes) {
		// index++;
		// Art.drawString(index + "a" + fish.type, Math.round(fish.getX()),
		// Math.round(fish.getY()));
		// }

		// underwaterStage.getCamera().position.set(xpos , ypos, 0);

		if (shutterEffect) {
			shutterCurr = System.currentTimeMillis();
			if (shutterCurr - shutterStart > 200
					&& shutterCurr - shutterStart < 3000) {
				underwaterStage.removeActor(underwaterStage.blitz);
			} else if (shutterCurr - shutterStart >= 3000) {
				shutterEffect = false;
				underwaterStage.addActor(underwaterStage.shutter);
			}
		} else {

		}

		// check input
		// if (Gdx.input.justTouched()){
		// for(int i=0; i<fishes.size(); i++){
		// if(kamera.isShot(fishes.get(i)) &&
		// targetFish==fishes.get(i).getType())
		// gamePoint += fishes.get(i).getPoint();
		// }
		// // System.out.println("point = "+gamePoint);
		// }

		if (gamePoint<=-1000){
			setGameToLose();
		}
		
		// check time
		
		if ((int) gameTime.getMinute() == 0 && (int) gameTime.getSecond() == 0)
			if (gamePoint < targetPoint) {
				setGameToLose();
			} else {
				setGameToWin();
			}
		// System.out.println("Time = "+gameTime.getMinute()+" "+gameTime.getSecond());
		// generate new target every 10 seconds
		if ((((int) gameTime.getSecond()) == 0)
				|| (((int) gameTime.getSecond()) % 10) == 0) {
			if (genTargetCurSecond != (int) gameTime.getSecond()) {
				genTargetCurSecond = (int) gameTime.getSecond();
				generateTarget();
			}
		}

		if ((((int) gameTime.getSecond()) == 0)
				|| (((int) gameTime.getSecond()) % 5) == 0) {
			if (genTargetCurSecond != (int) gameTime.getSecond()) {
				genTargetCurSecond = (int) gameTime.getSecond();
				generateNewFish();
			}
		}

		// move all fishes randomly
		// if((((int)gameTime.getSecond())==0) ||
		// (((int)(gameTime.getSecond()*10)) % 10)==0){
		if (moveFishCurSecond != (int) (gameTime.getSecond() * 10)) {
			moveFishCurSecond = (int) (gameTime.getSecond() * 10);
			for (Fish fish : fishes) {
				fish.move(stateTime);
				fish.checkFlip();
			}

		}
		// }
	}

	private void generateTarget() {
		// TODO Auto-generated method stub
		int temp = targetFish;
		while (targetFish == temp) {
			targetFish = randomizer.nextInt(12);
			targetFishReg = fishRegion[targetFish][0];
		}

	}

	private void generateNewFish() {
		fishes.add(new Fish(fishRegion[targetFish], targetFish, randomizer
				.nextInt(480 * 3 - 10), randomizer.nextInt(Gdx.graphics
				.getHeight() - 64), 1, randomizer));
	}

	@Override
	protected void onGameWin() {
		// TODO Auto-generated method stub
		// Art.drawString(underwaterStage.getSpriteBatch(),"you win", 0, 240);
		// Art.drawString(underwaterStage.getSpriteBatch(),""+score, 0, 240);

	}

	@Override
	protected void onGameLose() {
		// TODO Auto-generated method stub
		// Art.drawString(underwaterStage.getSpriteBatch(),"you lose", 0, 240);
		// Art.drawString(underwaterStage.getSpriteBatch(),""+score, 0, 240);

	}

	@Override
	protected void onGamePause() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onGameStart() {
		// TODO Auto-generated method stub
//		System.out.println(1);
		setCameraToDefault();
		gameTime.setMinute(1);
		gameTime.setSecond(0);

		// bestScore = Persistence.getBestScore(Persistence.UNDERWATER);
		gamePoint = 0;
		targetPoint = 1000;
		targetFish = 0;
		targetFishReg = fishRegion[targetFish][0];

		score = 0;
		shutterEffect = true;
//		if (underwaterStage.findActor("shutter"))
//		underwaterStage.addActor(underwaterStage.shutter);

	
		
		fishes.clear();
		// create fishes at left side
		// i<2 -> 3 species -> teri, tongkol, lele
		for (int i = 0; i < 2; i++) {
			// j<n -> n+1 = num of fish
			// generate fish at half left of the screen, vertically inside
			// camera range
			for (int j = 0; j < 3; j++) {
				int temp = randomizer.nextInt(12);
				fishes.add(new Fish(fishRegion[temp], temp, randomizer
						.nextInt(Constants.GAME_WIDTH * 3 - 100) + 50,
						randomizer.nextInt(Gdx.graphics.getHeight() - 64), 1,
						randomizer));
			}
		}

		// create fishes at right side
		for (int i = 0; i < 2; i++) {
			// j<n -> n+1 = num of fish
			// generate fish at half left of the screen, vertically inside
			// camera range
			for (int j = 0; j < 3; j++) {
				int temp = randomizer.nextInt(12);
				fishes.add(new Fish(fishRegion[temp], temp, randomizer
						.nextInt(Constants.GAME_WIDTH * 3 - 100) + 50, seaWidth
						- (randomizer.nextInt(Gdx.graphics.getHeight() - 64)),
						-1, randomizer));
			}
		}
		shutterStart = System.currentTimeMillis();
	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub
		super.hide();
		try {
			if (Persistence.sound) {
				if (komodoIsland.underwater.isPlaying()) {
					komodoIsland.underwater.stop();
				}
			} else {

			}
		} catch (Exception e) {

		}
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub
		super.show();
		try {
			if (Persistence.sound) {
				if (!komodoIsland.underwater.isPlaying()) {
					komodoIsland.underwater.play();
				}
			} else {

			}
		} catch (Exception e) {

		}
	}

	@Override
	protected void onGameLoading() {
		// TODO Auto-generated method stub
		// if (texture == null){

		if (swype == null) {
			swype = Gdx.audio.newMusic(Gdx.files
					.internal("sfx/underwater/swype.mp3"));
			swype.setLooping(false);
			swype.setVolume(0.5f);

		}
		if (click == null) {
			click = Gdx.audio.newSound(Gdx.files
					.internal("sfx/underwater/click.wav"));
		}

		if (komodoIsland.underwater == null) {
			komodoIsland.underwater = Gdx.audio.newMusic(Gdx.files
					.internal("bgm/underwater.wav"));
			komodoIsland.underwater.setLooping(true);
			komodoIsland.underwater.setVolume(0.5f);
		}

		if (Persistence.sound) {
			try {
				if (!komodoIsland.underwater.isPlaying()) {
					komodoIsland.underwater.play();
				}
			} catch (Exception e) {

			}
		}

		if (underwaterTexture == null)
			underwaterTexture = new Texture(
					Gdx.files.internal("underwater1.png"));

		if (winDialog == null)
			this.winDialog = new UnderwaterWinDialog(480, 320, true, this,
					komodoIsland.dialogTexture,komodoIsland);
		if (loseDialog == null)
			this.loseDialog = new UnderwaterLoseDialog(480, 320, true, this,
					komodoIsland.dialogTexture,komodoIsland);

		if (background == null)
			background = new TextureRegion(underwaterTexture, 0, 0, 1440, 320);
		if (fishRegion == null) {
			fishRegion = new TextureRegion[12][2];
			fishRegion[0] = new TextureRegion[2];
			fishRegion[1] = new TextureRegion[2];
			fishRegion[2] = new TextureRegion[2];
			fishRegion[3] = new TextureRegion[2];
			fishRegion[4] = new TextureRegion[2];
			fishRegion[5] = new TextureRegion[2];
			fishRegion[6] = new TextureRegion[2];
			fishRegion[7] = new TextureRegion[2];
			fishRegion[8] = new TextureRegion[2];
			fishRegion[9] = new TextureRegion[2];
			fishRegion[10] = new TextureRegion[2];
			fishRegion[11] = new TextureRegion[2];

			fishRegion[PARI][0] = new TextureRegion(underwaterTexture, 0, 320,
					128, 128);
			fishRegion[PARI][1] = new TextureRegion(underwaterTexture, 128,
					320, 128, 128);

			fishRegion[DUGONG][0] = new TextureRegion(underwaterTexture, 0,
					320 + 128, 128, 64);
			fishRegion[DUGONG][1] = new TextureRegion(underwaterTexture, 128,
					320 + 128, 128, 64);

			fishRegion[DOLPHIN][0] = new TextureRegion(underwaterTexture,
					128 * 2 + 96, 320, 128, 64);
			fishRegion[DOLPHIN][1] = new TextureRegion(underwaterTexture,
					128 * 3 + 96, 320, 128, 64);

			fishRegion[BARACUDDA][0] = new TextureRegion(underwaterTexture,
					128 * 2 + 96, 320 + 64, 128, 64);
			fishRegion[BARACUDDA][1] = new TextureRegion(underwaterTexture,
					128 * 3 + 96, 320 + 64, 128, 64);

			fishRegion[IKANUNGU][0] = new TextureRegion(underwaterTexture,
					128 * 2 + 96, 320 + 128, 64, 64);
			fishRegion[IKANUNGU][1] = new TextureRegion(underwaterTexture,
					128 * 2 + 96 + 64, 320 + 128, 64, 64);

			fishRegion[IKANLUPA][0] = new TextureRegion(underwaterTexture,
					128 * 3 + 96, 320 + 128, 64, 64);
			fishRegion[IKANLUPA][1] = new TextureRegion(underwaterTexture,
					128 * 3 + 96 + 64, 320 + 128, 64, 64);

			fishRegion[IKANKUNING][0] = new TextureRegion(underwaterTexture,
					128 * 4 + 96, 320, 64, 64);
			fishRegion[IKANKUNING][1] = new TextureRegion(underwaterTexture,
					128 * 4 + 96 + 64, 320, 64, 64);

			fishRegion[IKANANEH][0] = new TextureRegion(underwaterTexture,
					128 * 4 + 96, 320 + 64, 64, 64);
			fishRegion[IKANANEH][1] = new TextureRegion(underwaterTexture,
					128 * 4 + 96 + 64, 320 + 64, 64, 64);

			fishRegion[GURITA][0] = new TextureRegion(underwaterTexture,
					128 * 4 + 96, 320 + 128, 64, 64);
			fishRegion[GURITA][1] = new TextureRegion(underwaterTexture,
					128 * 4 + 94 + 64, 320 + 128, 64, 64);

			fishRegion[EPHIPPIDEA][0] = new TextureRegion(underwaterTexture,
					128 * 5 + 96, 320, 64, 64);
			fishRegion[EPHIPPIDEA][1] = new TextureRegion(underwaterTexture,
					128 * 5 + 64 + 96, 320, 64, 64);

			fishRegion[IKANBADUT][0] = new TextureRegion(underwaterTexture,
					128 * 5 + 96, 320 + 64, 64, 64);
			fishRegion[IKANBADUT][1] = new TextureRegion(underwaterTexture,
					128 * 5 + 64 + 96, 320 + 64, 64, 64);

			fishRegion[BINTANG][0] = new TextureRegion(underwaterTexture,
					128 * 5 + 96, 320 + 128, 64, 64);
			fishRegion[BINTANG][1] = new TextureRegion(underwaterTexture,
					128 * 5 + 64 + 96, 320 + 128, 64, 64);

		}
		if (targetText == null)
			targetText = new TextureRegion(underwaterTexture, 128 * 2,
					320 + 64 + 96, 96, 32);
		if (pointText == null)
			pointText = new TextureRegion(underwaterTexture, 128 * 6 + 96, 320,
					96, 32);
		if (bgTime == null)
			bgTime = new TextureRegion(underwaterTexture, 0, 0, 228, 32);

		if (underwaterStage == null)
			this.underwaterStage = new UnderwaterStage(480, 320, true, this,
					underwaterTexture,komodoIsland);

		// }
		if (timer ==null){
			timer = new Time(0, 59);
		}
		timer.setMinute(0);
		timer.setSecond(60);
	}

	@Override
	public void setScreenToRun() {
		// TODO Auto-generated method stub
		super.setScreenToRun();
		screenState = RUNNING;
		// komodoIsland.input.setStage(underwaterStage);
	}

	@Override
	public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		try {
			return super.touchDown(arg0, arg1, arg2, arg3)
					|| underwaterStage.touchDown(arg0, arg1, arg2, arg3);
		} catch (Exception e) {
			return super.touchDown(arg0, arg1, arg2, arg3);
		}
	}

	@Override
	public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

		try {
			return super.touchUp(arg0, arg1, arg2, arg3)
					|| underwaterStage.touchUp(arg0, arg1, arg2, arg3);
		} catch (Exception e) {
			return super.touchUp(arg0, arg1, arg2, arg3);
		}
	}

	@Override
	public boolean touchDragged(int arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

		try {
			return super.touchDragged(arg0, arg1, arg2)
					|| underwaterStage.touchDragged(arg0, arg1, arg2);
		} catch (Exception e) {
			return super.touchDragged(arg0, arg1, arg2);
		}
	}

	public void cekTarget() {
		boolean found = false;
		for (Fish fish : fishes) {
			float tempx = fish.getX();
			if ((tempx >= (xpos - 240)) && (tempx <= xpos + 240)) {
				if (fish.type == targetFish) {
					gamePoint += fish.point;
					score += fish.point;
					found = true;
				}

				if (randomizer.nextBoolean()) {
					fish.dir = -1;
					fish.setPosition(xpos - 240 - randomizer.nextInt(60),
							randomizer.nextInt(320 - 60));
				} else {
					fish.dir = 1;
					fish.setPosition(xpos + 240 + randomizer.nextInt(60),
							randomizer.nextInt(320 - 60));
				}

			}
		}
		if (found) {

		} else {
			score -= 200;
			gamePoint -= 200;
		}
		generateTarget();

	}

	protected class UnderwaterWinDialog extends WinDialog {

		public Image finish;
		
		public UnderwaterWinDialog(float width, float height, boolean stretch,
				Screen screen, Texture texture,KomodoIsland komodoIsland) {
			super(width, height, stretch, screen, texture,komodoIsland);
			// TODO Auto-generated constructor stub
		}
		

		@Override
		public void init() {
			// TODO Auto-generated method stub
			super.init();
			finish = new Image("finish", new TextureRegion(
					screen.komodoIsland.additionTexture, 0, 760+96, 96, 96));
		}

		@Override
		public void addElements() {
			// TODO Auto-generated method stub
			super.addElements();
			addActor(finish);
		}

		@Override
		public void setThePosition() {
			// TODO Auto-generated method stub
			super.setThePosition();
			finish.x = siKomo.x;
			finish.y = siKomo.y;

		}

	}

	protected class UnderwaterLoseDialog extends LoseDialog {

		public Image finish;
		
		public UnderwaterLoseDialog(float width, float height, boolean stretch,
				Screen screen, Texture texture,KomodoIsland komodoIsland) {
			super(width, height, stretch, screen, texture,komodoIsland);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void init() {
			// TODO Auto-generated method stub
			super.init();
			finish = new Image("finish", new TextureRegion(
					screen.komodoIsland.additionTexture, 96, 760+96, 95, 96));
		}

		@Override
		public void addElements() {
			// TODO Auto-generated method stub
			super.addElements();
			addActor(finish);
		}

		@Override
		public void setThePosition() {
			// TODO Auto-generated method stub
			super.setThePosition();
			finish.x = siKomo.x;
			finish.y = siKomo.y;

		}

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		super.dispose();

	}

	@Override
	public void cleanResScreen() {
		// TODO Auto-generated method stub
		super.cleanResScreen();
		try {
			underwaterStage.dispose();
			underwaterTexture.dispose();
			swype.dispose();
			click.dispose();
		} catch (Exception e) {

		}
	}
	
	@Override
	public void exitScreen() {
		// TODO Auto-generated method stub
		try {
			underwaterStage.dispose();
			underwaterTexture.dispose();
			swype.dispose();
			click.dispose();
			underwaterStage=null;
			underwaterTexture = null;
			swype = null;
			click = null;
		} catch (Exception e) {

		}
		super.exitScreen();
	}

}